<script>
	export default {
		onLaunch: function() {
			console.warn('当前组件仅支持 uni_modules 目录结构 ，请升级 HBuilderX 到 3.1.0 版本以上！')
			console.log('App Launch')
		},
		onShow: function() {
			// 获取冷启动路径
			const launchOptions = uni.getLaunchOptionsSync();
			if (launchOptions.path) {
				this.checkColdStart(launchOptions.path);
			}
			// this.checkLaunchPage();

			// 全局路由拦截
			const interceptors = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];

			interceptors.forEach(api => {
				uni.addInterceptor(api, {
					invoke: (args) => {
						this.checkAuth(args.url);
					}
				});
			});
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 获取默认页面配置（当页面未加载时）
			async getDefaultPageConfig(path) {
				// 动态导入 pages.json
				const pagesJson = (await import('@/pages.json')).default;
				const temp = pagesJson.pages.find(p => p.path === path)?.style;
				return temp;
			},
		
			// 修改检查冷启动方法为异步
			async checkColdStart(path) {
				const pageConfig = await this.getPageConfig(path);
				if (pageConfig?.requiresAuth && !uni.getStorageSync('token')) {
					uni.redirectTo({
						url: `/pages/login?redirect=${encodeURIComponent(path)}`
					});
				}
			},
		
			// 修改获取页面配置方法为异步
			async getPageConfig(path) {
				const pages = getCurrentPages();
				return pages.find(p => p.route === path)?.$page?.style || await this.getDefaultPageConfig(path);
			},
			// 检查冷启动第一个页面
			checkLaunchPage() {
				console.log('checkLaunchPage');
				const pages = getCurrentPages();
				console.log('pages', pages);
				if (pages.length === 0) return;
				const firstPage = pages[0];
				console.log(firstPage);
				if (firstPage.$page?.meta?.requiresAuth && !uni.getStorageSync('token')) {
					uni.redirectTo({
						url: `/pages/login?redirect=${encodeURIComponent(firstPage.$page.route)}`
					});
				}
			},
		
			// 统一权限检查
			checkAuth(url) {
				const route = url.split('?')[0];
				const pages = getCurrentPages();
				const pageConfig = pages.find(p => p.route === route)?.$page?.style;
		
				if (pageConfig?.requiresAuth && !uni.getStorageSync('token')) {
					uni.redirectTo({
						url: `/pages/login?redirect=${encodeURIComponent(url)}`
					});
					return false;
				}
				return true;
			}
		}
	}
</script>

<style lang="scss">
	 @import "./uni_modules/vk-uview-ui/index.scss";
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	/* #ifndef APP-NVUE */
	@import '@/static/customicons.css';
	/*每个页面公共css */
	@import './static/common.css';
	@import "@/static/iconfont.css";
	body{
		background-color: #f5f5f5;
	}
	// 设置整个项目的背景色
	page {
		background-color: #f5f5f5;
	}

	/* #endif */
	.example-info {
		font-size: 14px;
		color: #333;
		padding: 10px;
	}
	.page{
		height: 100vh;
		background-color: #f7f8fa;
	}
</style>
